<?php

class User extends Model {

    public $id;
    public $fullname;
    public $username;
    public $password;
    public $birthday;
    public $sex;
    public $email;
    public $picture;
    public $introduce;
    public $address;

    public function __construct($params = null) {
        parent::__construct();
        $this->_initialize($params);
    }

    public function login($username, $password) {
        $username = mysql_real_escape_string($username);
        $password = md5(mysql_real_escape_string($password));

        $sql = sprintf("SELECT *
				FROM `l4_user`
				WHERE username='%s' AND password='%s'", $username, $password);
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            $user = $this->getInfoByUsername($username);

            $_SESSION['user'] = array(
                'isLogin' => true,
                'info' => $user
            );
            header('Location:index.php');
        } else {
            return 'Username or password invalid';
        }
    }

    public static function logout() {
        if (!empty($_SESSION['user'])) {
            unset($_SESSION['user']);
            header('Location:index.php?c=login');
        }
    }

    public function getLocation($id) {
        if (empty($id)) {
            return false;
        }

        $sql = sprintf("SELECT `location` FROM `l4_user` WHERE `id`=%s", $id);
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            while ($row = mysql_fetch_object($this->db->result)) {
                return $row;
            }
        } else {
            return false;
        }
    }

    public function updateLocation($id, $location) {
        if (empty($id) || empty($location)) {
            return false;
        }

        $sql = "UPDATE `l4_user` SET `location`='%s' WHERE `id`=" . $this->id;
        $sql = sprintf($sql, mysql_real_escape_string($location), $id);
        $this->db->queryshort($sql, DB_NAME);
        $affectedRow = $this->db->affectedRow();

        if ($affectedRow >= 0) {
            $this->_updateSes1($id);
            return true;
        } else {
            return NULL;
        }

        return false;
    }

    public function registration($captcha) {
        $supThis = & getInstance();
        $supThis->library('validation');
        //Check user if existed.

        if (!is_null($this->getInfoByUsername($this->username))) {
            return "Username's already existed";
        }
        //Check validation...
        if (!(bool) validation::minLength($this->name, 4)) {
            return 'Fullname must be greater than four character';
        }

        if (!validation::validUsername($this->username)) {
            return 'Username can be only alpha and numberic and at least four character';
        }

        if (!validation::validPassword($this->password)) {
            return 'Password can be only alpha and numberic and at least four character.';
        }

        if (!(bool) validation::equalText($this->password, $this->repassword)) {
            return 'Password not match together';
        }

        if (!(bool) validation::validEmail($this->email)) {
            return 'Email is invalid';
        }

        if ((bool) $this->_isExistEmail($this->email)) {
            return 'Email is existed';
        }

        $birthday = date('d-m-Y', $this->birthday);
        $return = validation::birthday($birthday);

        if (!empty($return)) {
            return $return;
        }

        if (!(bool) validation::equalText($_SESSION['secure'], $captcha)) {
            return 'Captcha not match';
        }

        //Escape query string.
        foreach (array('name', 'email', 'username', 'password') as $property) {
            $this->$property = mysql_real_escape_string($this->$property);
        }
        $this->address = stripslashes($this->address);

        $sql = sprintf("INSERT INTO `l5_user`(`name`, `email`,`username`, `password`, `birthday`, `level`, `sex`, `address`)
				VALUES('%s', '%s', '%s', '%s', %s, %s, %s, '%s')", $this->name, $this->email, $this->username, md5(($this->password)), $this->birthday, 2, $this->sex, $this->address);

        $this->db->queryshort($sql, DB_NAME);
        $row_affected = $this->db->affectedRow();

        if ($row_affected > 0) {
            $this->_sendConfirm();

            return 'Registration successfully';
        } else {
            return 'Registration unsuccessfully';
        }
    }

    public function getInfoByUsername($username) {
        $sql = sprintf("SELECT *
				FROM `l4_user`
				WHERE `username`='%s'", mysql_real_escape_string($username));
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();
        if ($numRow > 0) {
            while ($row = mysql_fetch_object($this->db->result)) {
                return $row;
            }
        }

        return NULL;
    }

    private function _isExistUsername($username, $self = false, $id = 0) {
        if (trim($username) == '') {
            return FALSE;
        }
        $sql = sprintf("SELECT * FROM `l4_user` WHERE `username`='%s'", mysql_real_escape_string($username));
        if ((bool) $self) {
            $sql .= " AND `id` != {$id}";
        }

        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();
        if ($numRow > 0) {
            return TRUE;
        }
        return NULL;
    }

    public function getInfoById($id) {
        $sql = sprintf("SELECT * FROM `l4_user` WHERE id='%s'", $id);
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();
        if ($numRow > 0) {
            while ($row = mysql_fetch_object($this->db->result)) {
                return $row;
            }
        }

        return NULL;
    }

    public function getList(array $search = NULL, $offset = 0, $length = 8, array $orderby = array("id" => "ASC", 'name' => 'DESC')) {

        $sql = "SELECT * FROM `l5_user` WHERE 1=1 ";
        if ($offset < 0) {
            $offset = 0;
        }
        if ($length < 0) {
            $length = 8;
        }

        if (!empty($search)) {
            $sql .= "AND ";
            foreach ($search as $key => $val) {
                if (trim($val) != '') {
                    $sql .= $key . " LIKE '%" . $val . "%' AND ";
                }
            }
        }

        $sql = trim($sql, "AND ");

        if (!empty($orderby)) {
            $sql .= " ORDER BY ";
            foreach ($orderby as $key => $val) {
                $sql .= $key . " " . $val . ",";
            }
        }

        $sql = trim($sql, ",");
        $sql .= " LIMIT {$offset}, {$length}";
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            return $this->db->getArrayObject();
        } else {
            return null;
        }

        return;
    }

    public function gets($search = NULL) {
        //$sql = "SELECT * FROM `l4_user` WHERE `id` <>{$this->id} ";
        $sql = "SELECT DISTINCT a.*  FROM `l4_user` a 
                    LEFT JOIN `l4_friend_relation` b ON a.id = b.user_id_2 
                    LEFT JOIN `l4_friend_request` c ON a.id = c.to_user_id
                WHERE a.`id` <>". $this->id; 
        //var_dump($sql);
        if (!empty($search)) {
            $sql .= "AND ";
            foreach ($search as $key => $val) {
                if (trim($val) != '') {
                    $sql .= $key . " LIKE '%" . mysql_real_escape_string($val) . "%' AND ";
                }
            }
        }

        $sql = trim($sql, "AND ");

        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            return $this->db->getArrayObject();
        } else {
            return null;
        }

        return;
    }

    public function addFavorite($id = 0, $idFavorite = 0) {
        $sql = "INSERT INTO favorite(`member_id`, `favorite_member_id`, `create_datetime`) VALUES({$id},{$idFavorite}," . time() . ")";
        $this->db->queryshort($sql, DB_NAME);
        $affectedRow = $this->db->affectedRow();

        if ($affectedRow > 0) {
            return true;
        } else {
            return false;
        }

        return false;
    }

    public function getFavoriteUser($name = '', $sex = 0) {
        $sql = "SELECT *
		FROM `member` WHERE 1=1 ";

        if (!empty($name)) {
            $sql .= "AND `name` LIKE '%" . mysql_real_escape_string($name) . "%' ";
        }

        if (!empty($sex)) {
            $sql .= "AND `sex`=" . mysql_real_escape_string($sex);
        }

        $sql .= " AND `id` NOT IN(SELECT `favorite_member_id` FROM `favorite` WHERE `member_id`=" . $this->id . ") ";
        $sql .="AND `id`!=" . $this->id;
        $sql .=" AND `enable_search`=1";
        //$sql .=" ORDER BY create_datetime DESC";

        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            return $this->db->getArrayObject();
        } else {
            return null;
        }

        return;
    }

    public function getListFavorite() {
        if (empty($this->id)) {
            return false;
        }
        $sql = 'SELECT * FROM `member` WHERE `id` IN(SELECT `favorite_member_id` FROM `favorite` WHERE `member_id`=' . $this->id . ')';
        //$sql = 'SELECT * FROM `member` a INNER JOIN favorite b ON a.id = b.member_id
        //	WHERE `id` IN(SELECT `favorite_member_id` FROM `favorite` WHERE `member_id`=' . $this->id . ')
        //ORDER BY create_datetime DESC';

        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            return $this->db->getArrayObject();
        } else {
            return null;
        }

        return;
    }

    public function delete($id = 0) {
        if (empty($id)) {
            return false;
        }

        $sql = "DELETE FROM `l5_user` WHERE `id`=" . $id;
        $this->db->queryshort($sql, DB_NAME);
        $affectedRow = $this->db->affectedRow();

        if ($affectedRow > 0) {
            return true;
        } else {
            return false;
        }

        return false;
    }

    public function removeFavoriteMem($idFavorite = 0) {
        if (empty($idFavorite)) {
            return false;
        }

        $sql = "DELETE FROM `favorite` WHERE `favorite_member_id`=" . $idFavorite . " AND `member_id`=" . $this->id;
        $this->db->queryshort($sql, DB_NAME);
        $affectedRow = $this->db->affectedRow();

        if ($affectedRow > 0) {
            return true;
        } else {
            return false;
        }

        return false;
    }

    public function updateProfile($profile) {
        if (empty($profile)) {
            return false;
        }
        $return = '';
        $return = $this->_validateProfile($profile->name, $profile->value);

        if (!empty($return)) {
            return array('updated' => 0, 'name' => $profile->name, 'value' => htmlentities((mysql_real_escape_string($profile->value))), 'txt_error' => $return);
        }

        $sql = "UPDATE `l4_user` SET `" . $profile->name . "`='" . htmlentities((mysql_real_escape_string($profile->value))) . "' WHERE id=" . $this->id;
        $this->db->queryshort($sql, DB_NAME);
        $affectedRow = $this->db->affectedRow();

        if ($affectedRow >= 0) {
            $this->_updateSes1($this->id);
            return array('updated' => 1, 'name' => $profile->name, 'value' => (mysql_real_escape_string($profile->value)), 'txt_error:' => '');
        } else {
            return array('updated' => 0, 'name' => $profile->name, 'value' => htmlentities((mysql_real_escape_string($profile->value))), 'txt_error:' => $return);
        }

        return false;
    }

    private function _validateProfile($field, $value) {
        $superThis = & getInstance();
        $superThis->library('validation');
        switch (trim($field)) {
            case 'username': {
                    if (!(bool) validation::minLength($value, 4)) {
                        return 'Username must be greater than four character';
                    }

                    if (!validation::validUsername($value)) {
                        return 'Username can be only alpha and numberic and at least four character';
                    }

                    if (!is_null($this->_isExistUsername($value, true, $this->id))) {
                        return "Username is already existed";
                    }
                }
                break;
            case 'fullname': {
                    if (!(bool) validation::minLength($value, 4)) {
                        return 'Fullname must be greater than four character';
                    }
                }
                break;
            case 'email': {
                    if (!(bool) validation::validEmail($value)) {
                        return 'Email is invalid';
                    }

                    if ((bool) $this->_isExistEmail($value, true, $this->id)) {
                        return 'Email is existed';
                    }
                }
                break;
            case 'birthday': {
                    $birthday = date('d-m-Y', strtotime($value));
                    $return = '';
                    $return = validation::birthday($birthday);
                    return $return;
                }
                break;
            default: {
                    return '';
                }
                return '';
        }
    }

    private function _updateSes1($id) {
        if (empty($id)) {
            return false;
        }

        $user = $this->getInfoById($id);

        $_SESSION['user'] = array(
            'isLogin' => true,
            'info' => $user
        );

        return true;
    }

    private function _updateSes($username) {
        if (empty($username)) {
            return false;
        }

        $user = $this->getInfoByUsername($username);
        $_SESSION['user'] = array(
            'isLogin' => true,
            'info' => $user
        );

        return true;
    }

    public function updateAvatar($id = 0) {
        $isEmptyImage = false;

        if (empty($_FILES["file"]['name'])) {
            return array('updated' => 0, 'txtErr' => 'Please choose file image in type of gif, png, jpg, jpeg.');
        }

        if (isset($_FILES["file"]) && !empty($_FILES["file"]['name'])) {
            $profile = self::upload1($this->id);

            if (is_numeric($profile) && $profile == IMAGE_NOTIMG) {
                return array('updated' => 0, 'txtErr' => 'Please choose file image in type of gif, png, jpg, jpeg.');
            }
        }

        $sql = sprintf("UPDATE `l4_user` SET `picture`='%s' WHERE `id`=%s", $profile, $this->id);

        $this->db->queryshort($sql, DB_NAME);
        $affectedRow = $this->db->affectedRow();

        if ($affectedRow >= 0) {
            $this->_updateSes1($this->id);
            return array('updated' => 1, 'profile' => $profile);
            //return $profile;
        } else {
            return false;
        }

        return false;
    }

    public static function upload($id) {
        $allowedExts = array("jpg", "jpeg", "gif", "png");
        $extension = @end(explode(".", $_FILES["file"]["name"]));
        if ((($_FILES["file"]["type"] == "image/gif")
                || ($_FILES["file"]["type"] == "image/jpeg")
                || ($_FILES["file"]["type"] == "image/jpg")
                || ($_FILES["file"]["type"] == "image/png")
                || ($_FILES["file"]["type"] == "image/pjpeg"))
                && ($_FILES["file"]["size"] < 20000)
                && in_array($extension, $allowedExts)) {
            if ($_FILES["file"]["error"] > 0) {
                return IMAGE_ERROR;
            } else {
                if (file_exists('img/' . $id . '.gif')) {
                    @unlink('img/' . $id . '.gif');
                }
                move_uploaded_file($_FILES["file"]["tmp_name"], "img/" . $_FILES["file"]["name"]);
                rename('img/' . $_FILES["file"]["name"], 'img/' . $id . '.gif');
                return $id . '.gif';
            }
        } else {
            return IMAGE_NOTIMG;
        }
    }

    public static function upload1($id) {
        if (preg_match('/.*\.(jpg|gif|jpeg|png|bmp)$/', $_FILES["file"]["name"])) {
            if ($_FILES["file"]["error"] > 0) {
                return IMAGE_ERROR;
            } else {
                if (file_exists('img/profile/' . $id . '.jpeg')) {
                    @unlink('profile/' . $id . '.jpeg');
                }
                move_uploaded_file($_FILES["file"]["tmp_name"], "img/profile/" . $_FILES["file"]["name"]);
                rename('img/profile/' . $_FILES["file"]["name"], 'img/profile/' . $id . '.jpeg');
                return $id . '.jpeg';
            }
        } else {
            return IMAGE_NOTIMG;
        }
    }

    private function _sendConfirm() {
        $to = trim($this->email);
        if (empty($to)) {
            return 'Email is empty.';
        }

        $subject = "Confirm your registration.";
        $key = md5(rand(1, 1000));
        $sql = sprintf("UPDATE `l5_user` SET `code_confirm_email`='%s' ", $key);
        $sql .= " WHERE id=" . $this->db->getLastId();

        $this->db->queryshort($sql, DB_NAME);
        $numAffect = $this->db->affectedRow();

        if ($numAffect <= 0) {
            return 'Can not update to database.';
        }

        $message = sprintf("http://172.16.24.2/les4/index.php?c=register&m=confirm&account=%s&hash=%s", $this->username, $key);
        var_dump($message);
        $from = "noreply@lampart.com";
        $headers = "From:" . $from;
        mail($to, $subject, $message, "From:" . $from);
    }

    private function _isExistEmail($email, $self = false, $id = 0) {
        if (trim($email) == '') {
            return FALSE;
        }
        $sql = sprintf("SELECT * FROM `l4_user` WHERE `email`='%s'", mysql_real_escape_string($email));
        if ((bool) $self) {
            $sql .= " AND `id` != {$id}";
        }

        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();
        if ($numRow > 0) {
            return TRUE;
        }
        return NULL;
    }

    public function activeAccount($account, $hash) {
        $sql = sprintf("SELECT * FROM `l5_user` WHERE `username`='%s' AND `code_confirm_email`='%s'", $account, $hash);
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            $user = $this->db->getArrayObject();
            $user = $user[0];

            if ($user->actived == 1) {
                return 'Your account actived';
            }

            $sql = sprintf("UPDATE `l5_user` SET `actived`=1
					WHERE `username`='%s' AND `code_confirm_email`='%s'", $account, $hash);

            $this->db->queryshort($sql, DB_NAME);
            $numAffect = $this->db->affectedRow();

            if ($numAffect <= 0) {
                return 'Can not active your account';
            }

            return 'Your account is actived successfully';
        }

        return 'Your account is not existed to activate';
    }

    public function addPhoto() {
        $this->upload1(rand(1, 10000000));
    }

}

?>